<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.0.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.0.4">


  <link rel="mask-icon" href="/images/logo.svg?v=6.0.4" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.0.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  
  <meta name="keywords" content="技术博客,php,java,python,go" />


<meta name="description" content="看了下shopxo 的源码, 在这里记录下微信小程序登录授权的实现过程。 获取微信小程序用户信息需要用户点击授权按钮才可以获取，我们可以在「我的页面」对于非登录的用户跳转到登录页面，在登录页面要求用户授权登录。 我的用户页面user.js: 1234567891011121314151617181920212223242526272829303132333435363738394041424344">
<meta property="og:type" content="article">
<meta property="og:title" content="微信小程序授权登录实例">
<meta property="og:url" content="http://blog.yunshu168.com/posts/ba8c712f.html">
<meta property="og:site_name" content="树下千云">
<meta property="og:description" content="看了下shopxo 的源码, 在这里记录下微信小程序登录授权的实现过程。 获取微信小程序用户信息需要用户点击授权按钮才可以获取，我们可以在「我的页面」对于非登录的用户跳转到登录页面，在登录页面要求用户授权登录。 我的用户页面user.js: 1234567891011121314151617181920212223242526272829303132333435363738394041424344">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-12-04T11:25:35.763Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="微信小程序授权登录实例">
<meta name="twitter:description" content="看了下shopxo 的源码, 在这里记录下微信小程序登录授权的实现过程。 获取微信小程序用户信息需要用户点击授权按钮才可以获取，我们可以在「我的页面」对于非登录的用户跳转到登录页面，在登录页面要求用户授权登录。 我的用户页面user.js: 1234567891011121314151617181920212223242526272829303132333435363738394041424344">






  <link rel="canonical" href="http://blog.yunshu168.com/posts/ba8c712f.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>
  <title>微信小程序授权登录实例 | 树下千云</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f8a99180bb75f49a4b2206cab6e25c50";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <!-- <div class="headband"></div>
<a href="https://github.com/yunshu2009"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a> -->
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">树下千云</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


  



 </div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.yunshu168.com/posts/ba8c712f.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="云舒">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="树下千云">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">微信小程序授权登录实例</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <!--<span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>-->
              
                <!--<span class="post-meta-item-text">发表于</span>-->
              
              <!--<time title="创建于" itemprop="dateCreated datePublished" datetime="2019-01-13T22:01:44+08:00">2019-01-13</time>-->
            

            
            

            
          </span>

          

          
            
          

          
          

          


          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>看了下<code>shopxo</code> 的源码, 在这里记录下微信小程序登录授权的实现过程。</p>
<p>获取微信小程序用户信息需要用户点击授权按钮才可以获取，我们可以在「我的页面」对于非登录的用户跳转到登录页面，在登录页面要求用户授权登录。</p>
<h3 id="我的用户页面"><a href="#我的用户页面" class="headerlink" title="我的用户页面"></a>我的用户页面</h3><p><code>user.js</code>:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> app = getApp();</span><br><span class="line"></span><br><span class="line">Page(&#123;</span><br><span class="line">  data: &#123;</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">  &#125;,</span><br><span class="line">  onShow() &#123;</span><br><span class="line">    wx.setNavigationBarTitle(&#123;<span class="attr">title</span>: app.data.common_pages_title.user&#125;);</span><br><span class="line">    <span class="keyword">this</span>.init();</span><br><span class="line">  &#125;,</span><br><span class="line">  init(e) &#123;</span><br><span class="line">    <span class="comment">// 从缓存中获取用户信息</span></span><br><span class="line">    <span class="keyword">var</span> user = app.get_user_cache_info(),</span><br><span class="line">        self = <span class="keyword">this</span>;</span><br><span class="line">    <span class="comment">// 用户未绑定用户则转到登录页面</span></span><br><span class="line">    <span class="keyword">var</span> msg = (user == <span class="literal">false</span>) ? <span class="string">'授权用户信息'</span> : <span class="string">'绑定手机号码'</span>;</span><br><span class="line">    <span class="keyword">if</span> (app.user_is_need_login(user)) &#123;</span><br><span class="line">      wx.showModal(&#123;</span><br><span class="line">        title: <span class="string">'温馨提示'</span>,</span><br><span class="line">        content: msg,</span><br><span class="line">        confirmText: <span class="string">'确认'</span>,</span><br><span class="line">        cancelText: <span class="string">'暂不'</span>,</span><br><span class="line">        success: <span class="function">(<span class="params">result</span>) =&gt;</span> &#123;</span><br><span class="line">          <span class="comment">// 停止当前页面下拉刷新</span></span><br><span class="line">          wx.stopPullDownRefresh();</span><br><span class="line">          <span class="keyword">if</span>(result.confirm) &#123;</span><br><span class="line">            wx.navigateTo(&#123;</span><br><span class="line">              url: <span class="string">"/pages/login/login?event_callback=init"</span></span><br><span class="line">            &#125;);</span><br><span class="line">          &#125;</span><br><span class="line">          self.setData(&#123;</span><br><span class="line">            avatar: user.avatar || app.data.default_user_head_src,</span><br><span class="line">            nickname: user.user_name_view || <span class="string">'用户名'</span>,</span><br><span class="line">          &#125;);</span><br><span class="line">        &#125;,</span><br><span class="line">      &#125;);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 获取页面展示信息 </span></span><br><span class="line">      self.get_data();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  .</span><br><span class="line">  .</span><br><span class="line">  .</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<a id="more"></a>
<h3 id="登录页面处理"><a href="#登录页面处理" class="headerlink" title="登录页面处理"></a>登录页面处理</h3><p><code>login.wxml</code>:</p>
<p>展示授权登录按钮：<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">.</span><br><span class="line">.</span><br><span class="line">.</span><br><span class="line"><span class="tag">&lt;<span class="name">view</span> <span class="attr">wx:if</span>=<span class="string">"&#123;&#123;user == null&#125;&#125;"</span> <span class="attr">class</span>=<span class="string">"user-login tc"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">view</span> <span class="attr">class</span>=<span class="string">"cr-888 fs-12"</span>&gt;</span>确认登录授权，为您提供更优质的服务<span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">button</span> <span class="attr">type</span>=<span class="string">"primary"</span> <span class="attr">size</span>=<span class="string">"mini"</span> <span class="attr">open-type</span>=<span class="string">"getUserInfo"</span> <span class="attr">bindgetuserinfo</span>=<span class="string">"get_user_info_event"</span>&gt;</span>授权登录<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p><code>login.js</code>：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> app = getApp();</span><br><span class="line"></span><br><span class="line">Page(&#123;</span><br><span class="line">    data:&#123;</span><br><span class="line">        user:<span class="literal">null</span>,</span><br><span class="line">        .</span><br><span class="line">        .</span><br><span class="line">        .</span><br><span class="line">    &#125;,</span><br><span class="line">     <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 页面加载初始化</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  onLoad(option) &#123;</span><br><span class="line">    <span class="comment">// 设置用户信息</span></span><br><span class="line">    <span class="keyword">this</span>.setData(&#123;</span><br><span class="line">      .</span><br><span class="line">      .</span><br><span class="line">      .</span><br><span class="line">      <span class="comment">// 从缓存中获取用户信息</span></span><br><span class="line">      user: app.get_user_cache_info() || <span class="literal">null</span></span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 标题设置</span></span><br><span class="line">    wx.setNavigationBarTitle(&#123; <span class="attr">title</span>: (<span class="keyword">this</span>.data.user == <span class="literal">null</span>) ? <span class="string">'授权用户信息'</span> : <span class="string">'手机绑定'</span> &#125;);</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// button 绑定的登录授权事件， 回调参数见：https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html</span></span><br><span class="line">  get_user_info_event(e) &#123;</span><br><span class="line">    <span class="keyword">this</span>.user_auth_code(<span class="literal">null</span>, <span class="literal">null</span>, e.detail);</span><br><span class="line">  &#125;,</span><br><span class="line">  </span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 用户授权</span></span><br><span class="line"><span class="comment">   * object     回调操作对象</span></span><br><span class="line"><span class="comment">   * method     回调操作对象的函数</span></span><br><span class="line"><span class="comment">   * auth_data  授权数据</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  user_auth_code(object, method, auth_data) &#123;</span><br><span class="line">    <span class="comment">// 请求授权接口</span></span><br><span class="line">    <span class="keyword">var</span> self = <span class="keyword">this</span>;</span><br><span class="line">    <span class="comment">// 获取用户当前的授权状态，https://developers.weixin.qq.com/miniprogram/dev/api/open-api/setting/wx.getSetting.html </span></span><br><span class="line">    wx.getSetting(&#123;</span><br><span class="line">      success(res) &#123;</span><br><span class="line">        <span class="comment">// 判断是否授权用户信息</span></span><br><span class="line">        <span class="keyword">if</span> (! res.authSetting[<span class="string">'scope.userInfo'</span>]) &#123; </span><br><span class="line">          self.setData(&#123; <span class="attr">user</span>: <span class="literal">null</span>&#125;);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          app.user_auth_login(self, <span class="string">'user_auth_back_event'</span>, auth_data);</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;,</span><br><span class="line">      fail: <span class="function">(<span class="params">e</span>) =&gt;</span> &#123;</span><br><span class="line">        app.showToast(<span class="string">"授权校验失败"</span>);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="授权登录操作"><a href="#授权登录操作" class="headerlink" title="授权登录操作"></a>授权登录操作</h3><p>见<code>app.js</code>中的<code>user_auth_login()</code>：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br></pre></td><td class="code"><pre><span class="line">App(&#123;</span><br><span class="line">  data: &#123;</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 用户登录</span></span><br><span class="line"><span class="comment">   * object     回调操作对象</span></span><br><span class="line"><span class="comment">   * method     回调操作对象的函数</span></span><br><span class="line"><span class="comment">   * auth_data  授权数据</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  user_auth_login(object, method, auth_data) &#123;</span><br><span class="line">    wx.showLoading(&#123; <span class="attr">title</span>: <span class="string">"授权中..."</span> &#125;);</span><br><span class="line">    <span class="keyword">var</span> self = <span class="keyword">this</span>;</span><br><span class="line">    wx.checkSession(&#123;</span><br><span class="line">      <span class="comment">// 检查登录态是否过期 https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.checkSession.html</span></span><br><span class="line">      success: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> openid = wx.getStorageSync(self.data.cache_user_login_key) || <span class="literal">null</span>;</span><br><span class="line">        <span class="keyword">if</span> (openid == <span class="literal">null</span>) &#123;</span><br><span class="line">          self.user_login(object, method, auth_data);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          self.get_user_login_info(object, method, openid, auth_data);</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;,</span><br><span class="line">      fail: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        self.user_login(object, method, auth_data);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;,</span><br><span class="line">  </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 用户登录</span></span><br><span class="line"><span class="comment">   * object     回调操作对象</span></span><br><span class="line"><span class="comment">   * method     回调操作对象的函数</span></span><br><span class="line"><span class="comment">   * auth_data  授权数据</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  user_login(object, method, auth_data) &#123;</span><br><span class="line">    <span class="keyword">var</span> self = <span class="keyword">this</span>;</span><br><span class="line">    wx.login(&#123;</span><br><span class="line">      success: <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (res.code) &#123;</span><br><span class="line">          wx.request(&#123;</span><br><span class="line">            url: self.get_request_url(<span class="string">'wechatuserauth'</span>, <span class="string">'user'</span>),</span><br><span class="line">            method: <span class="string">'POST'</span>,</span><br><span class="line">            data: &#123; <span class="attr">authcode</span>: res.code &#125;,</span><br><span class="line">            dataType: <span class="string">'json'</span>,</span><br><span class="line">            header: &#123; <span class="string">'content-type'</span>: <span class="string">'application/x-www-form-urlencoded'</span> &#125;,</span><br><span class="line">            success: <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">              <span class="keyword">if</span> (res.data.code == <span class="number">0</span>) &#123;</span><br><span class="line">                wx.setStorage(&#123;</span><br><span class="line">                  key: self.data.cache_user_login_key,</span><br><span class="line">                  data: res.data.data  <span class="comment">// 用户 Open ID</span></span><br><span class="line">                &#125;);</span><br><span class="line">                self.get_user_login_info(object, method, res.data.data, auth_data);</span><br><span class="line">              &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                wx.hideLoading();</span><br><span class="line">                self.showToast(res.data.msg);</span><br><span class="line">              &#125;</span><br><span class="line">            &#125;,</span><br><span class="line">            fail: <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">              wx.hideLoading();</span><br><span class="line">              self.showToast(<span class="string">'服务器请求出错'</span>);</span><br><span class="line">            &#125;,</span><br><span class="line">          &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;,</span><br><span class="line">      fail: <span class="function">(<span class="params">e</span>) =&gt;</span> &#123;</span><br><span class="line">        wx.hideLoading();</span><br><span class="line">        self.showToast(<span class="string">'授权失败'</span>);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;,</span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 微信小程序获取用户信息，将用户信息添加添加进数据库</span></span><br><span class="line"><span class="comment">   * object     回调操作对象</span></span><br><span class="line"><span class="comment">   * method     回调操作对象的函数</span></span><br><span class="line"><span class="comment">   * openid     用户openid</span></span><br><span class="line"><span class="comment">   * auth_data  授权数据</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  get_user_login_info(object, method, openid, auth_data) &#123;</span><br><span class="line">    <span class="comment">// 邀请人参数</span></span><br><span class="line">    <span class="keyword">var</span> params = wx.getStorageSync(<span class="keyword">this</span>.data.cache_launch_info_key) || <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">var</span> referrer = (params == <span class="literal">null</span>) ? <span class="number">0</span> : (params.referrer || <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 远程解密数据</span></span><br><span class="line">    <span class="keyword">var</span> self = <span class="keyword">this</span>;</span><br><span class="line">    wx.request(&#123;</span><br><span class="line">      url: self.get_request_url(<span class="string">'wechatuserinfo'</span>, <span class="string">'user'</span>),</span><br><span class="line">      method: <span class="string">'POST'</span>,</span><br><span class="line">      data: &#123;</span><br><span class="line">        <span class="string">"encrypted_data"</span>: auth_data.encryptedData,</span><br><span class="line">        <span class="string">"iv"</span>: auth_data.iv,</span><br><span class="line">        <span class="string">"openid"</span>: openid,</span><br><span class="line">        <span class="string">"referrer"</span>: referrer</span><br><span class="line">      &#125;,</span><br><span class="line">      dataType: <span class="string">'json'</span>,</span><br><span class="line">      header: &#123; <span class="string">'content-type'</span>: <span class="string">'application/x-www-form-urlencoded'</span> &#125;,</span><br><span class="line">      success: <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        wx.hideLoading();</span><br><span class="line">        <span class="keyword">if</span> (res.data.code == <span class="number">0</span>) &#123;</span><br><span class="line">          wx.setStorage(&#123;</span><br><span class="line">            key: self.data.cache_user_info_key,</span><br><span class="line">            data: res.data.data,</span><br><span class="line">            success: <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">              <span class="keyword">if</span> (<span class="keyword">typeof</span> object === <span class="string">'object'</span> &amp;&amp; (method || <span class="literal">null</span>) != <span class="literal">null</span>) &#123;</span><br><span class="line">                object[method]();   <span class="comment">// 执行登录页面的 user_auth_back_event(),跳回到我的用户页面</span></span><br><span class="line">              &#125;</span><br><span class="line">            &#125;,</span><br><span class="line">            fail: <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">              self.showToast(<span class="string">'用户信息缓存失败'</span>);</span><br><span class="line">            &#125;</span><br><span class="line">          &#125;);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          self.showToast(res.data.msg);</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;,</span><br><span class="line">      fail: <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        wx.hideLoading();</span><br><span class="line">        self.showToast(<span class="string">'服务器请求出错'</span>);</span><br><span class="line">      &#125;,</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;,</span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">  /**</span></span><br><span class="line"><span class="comment">   * 请求地址生成</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  get_request_url(a, c, m, params) &#123;</span><br><span class="line">    a = a || <span class="string">"index"</span>;</span><br><span class="line">    c = c || <span class="string">"index"</span>;</span><br><span class="line">    m = m || <span class="string">"api"</span>;</span><br><span class="line">    params = params || <span class="string">""</span>;</span><br><span class="line">    <span class="keyword">if</span> (params != <span class="string">""</span> &amp;&amp; params.substr(<span class="number">0</span>, <span class="number">1</span>) != <span class="string">"&amp;"</span>) &#123;</span><br><span class="line">      params = <span class="string">"&amp;"</span> + params;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">var</span> user = <span class="keyword">this</span>.get_user_cache_info();</span><br><span class="line">    <span class="keyword">var</span> token = (user == <span class="literal">false</span>) ? <span class="string">''</span> : user.token || <span class="string">''</span>;</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      <span class="keyword">this</span>.data.request_url +</span><br><span class="line">      <span class="string">"index.php?s=/"</span> + m + <span class="string">"/"</span> + c + <span class="string">"/"</span> + a +</span><br><span class="line">      <span class="string">"&amp;application=app&amp;application_client_type=weixin"</span> +</span><br><span class="line">      <span class="string">"&amp;token="</span> +</span><br><span class="line">      token +</span><br><span class="line">      <span class="string">"&amp;ajax=ajax"</span> +</span><br><span class="line">      params</span><br><span class="line">    );</span><br><span class="line">  &#125;,</span><br><span class="line">  .</span><br><span class="line">  .</span><br><span class="line">  .</span><br><span class="line">  </span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="服务端根据-encryptedData-获取用户信息"><a href="#服务端根据-encryptedData-获取用户信息" class="headerlink" title="服务端根据 encryptedData 获取用户信息"></a>服务端根据 encryptedData 获取用户信息</h3><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">WechatUserInfo</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// 参数校验</span></span><br><span class="line">    $p = [</span><br><span class="line">        [</span><br><span class="line">            <span class="string">'checked_type'</span>      =&gt; <span class="string">'empty'</span>,</span><br><span class="line">            <span class="string">'key_name'</span>          =&gt; <span class="string">'openid'</span>,</span><br><span class="line">            <span class="string">'error_msg'</span>         =&gt; <span class="string">'openid为空'</span>,</span><br><span class="line">        ],</span><br><span class="line">        [</span><br><span class="line">            <span class="string">'checked_type'</span>      =&gt; <span class="string">'empty'</span>,</span><br><span class="line">            <span class="string">'key_name'</span>          =&gt; <span class="string">'encrypted_data'</span>,</span><br><span class="line">            <span class="string">'error_msg'</span>         =&gt; <span class="string">'解密数据为空'</span>,</span><br><span class="line">        ],</span><br><span class="line">        [</span><br><span class="line">            <span class="string">'checked_type'</span>      =&gt; <span class="string">'empty'</span>,</span><br><span class="line">            <span class="string">'key_name'</span>          =&gt; <span class="string">'iv'</span>,</span><br><span class="line">            <span class="string">'error_msg'</span>         =&gt; <span class="string">'iv为空,请重试'</span>,</span><br><span class="line">        ]</span><br><span class="line">    ];</span><br><span class="line">    $ret = ParamsChecked(<span class="keyword">$this</span>-&gt;data_post, $p);</span><br><span class="line">    <span class="keyword">if</span>($ret !== <span class="keyword">true</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">return</span> DataReturn($ret, <span class="number">-1</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 先从数据库获取用户信息</span></span><br><span class="line">    $user = UserService::AppUserInfoHandle(<span class="keyword">null</span>, <span class="string">'weixin_openid'</span>, <span class="keyword">$this</span>-&gt;data_post[<span class="string">'openid'</span>]);</span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">empty</span>($user))</span><br><span class="line">    &#123;</span><br><span class="line">            <span class="comment">// 解密用户信息，</span></span><br><span class="line">        $result = (<span class="keyword">new</span> \base\Wechat(MyC(<span class="string">'common_app_mini_weixin_appid'</span>), MyC(<span class="string">'common_app_mini_weixin_appsecret'</span>)))-&gt;DecryptData(<span class="keyword">$this</span>-&gt;data_post[<span class="string">'encrypted_data'</span>], <span class="keyword">$this</span>-&gt;data_post[<span class="string">'iv'</span>], <span class="keyword">$this</span>-&gt;data_post[<span class="string">'openid'</span>]);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(is_array($result))</span><br><span class="line">        &#123;</span><br><span class="line">            $result[<span class="string">'nick_name'</span>] = <span class="keyword">isset</span>($result[<span class="string">'nickName'</span>]) ? $result[<span class="string">'nickName'</span>] : <span class="string">''</span>;</span><br><span class="line">            $result[<span class="string">'avatar'</span>] = <span class="keyword">isset</span>($result[<span class="string">'avatarUrl'</span>]) ? $result[<span class="string">'avatarUrl'</span>] : <span class="string">''</span>;</span><br><span class="line">            $result[<span class="string">'gender'</span>] = <span class="keyword">empty</span>($result[<span class="string">'gender'</span>]) ? <span class="number">0</span> : ($result[<span class="string">'gender'</span>] == <span class="number">2</span>) ? <span class="number">1</span> : <span class="number">2</span>;</span><br><span class="line">            $result[<span class="string">'weixin_unionid'</span>] = <span class="keyword">isset</span>($result[<span class="string">'unionId'</span>]) ? $result[<span class="string">'unionId'</span>] : <span class="string">''</span>;</span><br><span class="line">            $result[<span class="string">'openid'</span>] = $result[<span class="string">'openId'</span>];</span><br><span class="line">            $result[<span class="string">'referrer'</span>]= <span class="keyword">isset</span>(<span class="keyword">$this</span>-&gt;data_post[<span class="string">'referrer'</span>]) ? <span class="keyword">$this</span>-&gt;data_post[<span class="string">'referrer'</span>] : <span class="number">0</span>;</span><br><span class="line">            <span class="comment">// 将用户信息添加进数据库</span></span><br><span class="line">            <span class="keyword">return</span> UserService::AuthUserProgram($result, <span class="string">'weixin_openid'</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> DataReturn(<span class="string">'授权成功'</span>, <span class="number">0</span>, $user);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> DataReturn(<span class="keyword">empty</span>($result) ? <span class="string">'获取用户信息失败'</span> : $result, <span class="number">-100</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p> 涉及到的解密用户数据接口： <a href="https://gitee.com/gongfuxiang/shopxo/blob/master/extend/base/Wechat.php" target="_blank" rel="noopener">https://gitee.com/gongfuxiang/shopxo/blob/master/extend/base/Wechat.php</a> </p>
<p><code>shopxo</code> 服务端 <code>controller</code> 的方法都是请求 <code>service</code> 的静态方法，然后在静态方法里调用用 <code>Db</code>, 没有使用<code>Model</code>层，如上面涉及到的 <code>UserService</code>，见：<a href="https://gitee.com/gongfuxiang/shopxo/blob/master/application/service/UserService.php" target="_blank" rel="noopener">https://gitee.com/gongfuxiang/shopxo/blob/master/application/service/UserService.php</a></p>

      
    </div>

    

    
    
    
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------本文结束<i class="fa fa-paw"></i>感谢阅读------</div>
    
</div>
  
</div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欣赏此文？求鼓励，求支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="云舒 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="云舒 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>云舒</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.yunshu168.com/posts/ba8c712f.html" title="微信小程序授权登录实例">http://blog.yunshu168.com/posts/ba8c712f.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/61184f26.html" rel="next" title="shopxo开源商城代码分析">
                <i class="fa fa-chevron-left"></i> shopxo开源商城代码分析
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/7feb99a9.html" rel="prev" title="laravelshop开源项目学习笔记">
                laravelshop开源项目学习笔记 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="云舒" />
            
              <p class="site-author-name" itemprop="name">云舒</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives">
                
                    <span class="site-state-item-count">68</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">28</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/yunshu2009" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:yunshu.luo@gmail.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.cnblogs.com/luoyunshu/" target="_blank" title="Cnblogs"><i class="fa fa-fw fa-globe"></i>Cnblogs</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.bilibili.com" target="_blank" title="bilibili"><i class="fa fa-fw fa-globe"></i>bilibili</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#我的用户页面"><span class="nav-number">1.</span> <span class="nav-text">我的用户页面</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#登录页面处理"><span class="nav-number">2.</span> <span class="nav-text">登录页面处理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#授权登录操作"><span class="nav-number">3.</span> <span class="nav-text">授权登录操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#服务端根据-encryptedData-获取用户信息"><span class="nav-number">4.</span> <span class="nav-text">服务端根据 encryptedData 获取用户信息</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2012 &mdash; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">云舒</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Pisces</a></div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.4"></script>



  



	





  





  






<!-- LOCAL: You can save these files to your site and update links -->
    
        
         <!-- <link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css"> -->
        <!-- <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script> -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/default.css">
        <script src="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/gitment.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitment({
            id: decodeURI(window.location.pathname),
            owner: 'yunshu2009',
            repo: 'yunshu2009.github.io',
            
            oauth: {
            
            
                client_secret: '15cdd9dc30fb9e0c97260bf79fe09d158fa04b22',
            
                client_id: '9495da16cda475a5e221'
            }});
        gitment.render('gitment-container');
      }

      
      renderGitment();
      
      </script>
    






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  


</body>
</html>
